/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import React from 'react';
import { AnyAction } from 'redux';

type Reducer<S> = (state: S, action: AnyAction) => S;

// 定义任务状态的枚举
enum TaskStatus {
  等待中 = 1,
  '导入中...' = 2,
  成功 = 3,
  终止 = 4,
}

export type TaskUploadStatus = 'pending' | 'in_progress' | 'completed' | 'failed';

// 获取任务的中文状态
export function getStatusText(status: TaskStatus): string {
  return TaskStatus[status] || '未知状态';
}
export interface Task {
  id: React.Key; // 序号
  brandName: string; // 品牌
  brandCode: string; // 品牌 code
  seriesName: string; // 车系
  seriesCode: string; // 车系 code
  modelName: string; // 车型
  modelCode: string; // 车型 code
  version: string; // 版本
  status: 1 | 2 | 3 | 4; // 任务状态
}
export interface TaskModel {
  namespace: 'task';
  state: {
    tasks: Task[];
    disabled: boolean;
    taskTotal: number;
    current: number;
  };
  reducers: {
    addTasks: Reducer<TaskModel['state']>;
    clearTasks: Reducer<TaskModel['state']>;
    updateTaskStatus: Reducer<TaskModel['state']>;
    updateAllTaskStatus: Reducer<TaskModel['state']>;
  };
}

const taskModel: TaskModel = {
  namespace: 'task',

  state: {
    tasks: [], // 存储任务列表的数组
    disabled: false,
    taskTotal: 0,
    current: 0,
  },

  reducers: {
    // 添加任务
    addTasks(state, { payload: newTasks = [] }) {
      return {
        ...state,
        tasks: [...newTasks],
        taskTotal: newTasks.length,
        current: 0,
      };
    },

    // 清空任务
    clearTasks(state) {
      return {
        ...state,
        tasks: [],
        taskTotal: 0,
        current: 0,
        disabled: false,
      };
    },

    // 更新任务状态
    updateTaskStatus(state, { payload: { taskId, newStatus, disabled } }) {
      let current = 0;
      const updatedTasks = state.tasks.map((task, index) => {
        if (task.id === taskId) {
          current = index + 1;
          return {
            ...task,
            status: newStatus,
          };
        }
        return task;
      });

      return {
        ...state,
        tasks: updatedTasks,
        current,
        disabled,
      };
    },

    // 更新全部任务状态
    updateAllTaskStatus(state) {
      let current = 0;
      const updatedTasks = state.tasks.map((task, index) => {
        if (task.status !== 3) { // 把所有不等于
          task.status = 4;
        }
        return task;
      });

      return {
        ...state,
        tasks: updatedTasks,
        current,
        disabled: false,
      };
    },
  },
};

export default taskModel;
